import 'package:bloc/bloc.dart';
import 'package:flutter_test_demo/database/index.dart';
import 'package:flutter_test_demo/model/index.dart';

import 'state.dart';

class OrderBlocCubit extends Cubit<OrderBlocState> {
  OrderBlocCubit() : super(OrderBlocState().init()) {
    initData();
  }

  void initData() async {
    state.orderList = await MethodDao.queryOrderList();
    state.orderItemList = await MethodDao.queryOrderItemList();
    getOrderList();
  }

  void getOrderList() {
    if(state.orderList.isNotEmpty) {
      for (var e in state.orderList) {
        OrderListModel model = OrderListModel();
        if(state.orderItemList.isNotEmpty) {
          List<OrderItemList> list = [];
          for (var w in state.orderItemList) {
            if(w.orderId == e.orderId) {
              model.orderId = e.orderId;
              model.orderDoc = e.orderDoc;
              model.payWay = e.payWay;
              model.totalPrice = e.totalPrice;
              model.orderTime = e.orderTime;
              OrderItemList t = OrderItemList();
              t.orderId = w.orderId;
              t.id = w.id;
              t.orderGoodsQty = w.orderGoodsQty;
              t.orderGoodsPrice = w.orderGoodsPrice;
              t.orderGoodsCode = w.orderGoodsCode;
              t.orderGoodsName = w.orderGoodsName;
              list.add(t);
            }
          }
          model.itemList = list;
        }
        state.realOrderList.add(model);
      }
      emit(state.clone()..realOrderList = state.realOrderList);
    }
  }

  num orderCountOrPrice({required int type}) {
    int count = 0;
    num price = 0;
    if(state.realOrderList.isNotEmpty) {
      String dateTime = DateTime.now().toString().substring(0, 10);
      for (var e in state.realOrderList) {
        if(e.orderTime != null) {
          String date = e.orderTime!.toString().substring(0, 10);
          if(date == dateTime) {
            if(type == 1) {
              count +=1;
            } else if(type == 2) {
              price += e.totalPrice ?? 0;
            }
          }
        }
      }
    }
    return type == 1 ? count : type == 2 ? price : 0;
  }

}
